util = require 'util'

module.exports = (app, User, School) ->
  app.post '/users/validate', (req, res) ->
    if not req.body.u or req.body.u == '' or not req.body.p or req.body.p == ''
      res.json { error: true }
    User.find { un: req.body.u }, (err, docs) ->
      if docs.length is 1
        send_user req, res, docs[0]
      else if req.body.u.length is 3
        find_school req, res, User, School
      else
        res.json { error: true }
  app.post '/users/logout', (req, res) ->
    User.find { un: req.body.u }, (err, docs) ->
      unless docs.length is 1 and docs[0].tk is req.body.tk
        res.json { error: true }
        return
      docs[0].tk = null
      res.json { error: !docs[0].save() }

generate_token = ->
  string = ""
  for i in [1..24]
    string += String.fromCharCode Math.floor(Math.random() * 26 + 1) + 0x30
  string

recalculate_points = (progress) ->
  points = 0
  for vocab in progress
    points += vocab.pr - 50 if vocab.pr > 50
  points

send_user = (req, res, user) ->
  if user.pw is req.body.p
    user.tk = generate_token()
    json =
      rn: user.rn
      em: user.em
      tk: user.tk
    res.json json
  else
    res.json { error: true }

find_school = (req, res, User, School) ->
  School.find { si: req.body.u, pw: req.body.p }, (err, docs) ->
    if docs.length is 1
      docs[0].tk = generate_token()
      docs[0].save()
      User.find { sc: docs[0].sn }, (err, users) ->
        students = []
        staff = []
        for user in users
          if user.tc
            staff.push user
          else
            students.push user
        res.json {
          control: true
          tk: docs[0].tk
          sn: docs[0].sn
          si: docs[0].si
          sl: docs[0].sl
          st: students
          tc: staff
          sp: docs[0].sp
          se: docs[0].se
          tp: docs[0].tp
          te: docs[0].te
        }
    else
      res.json { error: true }
